package com.xidian.zhiancloud.service.chemicalsManagement.chemicalManager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.CodeMapper;
import com.xidian.zhiancloud.model.Code;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 　　* @program zhiancloud
 * 　　* @author Egoist
 * 　　* @create 2021/2/28 16:03
 */
@Service
public class CodeService extends ServiceImpl<CodeMapper, Code> implements IService<Code> {

    public Long createCodeByCompany(Long companyId) {
        Code code = new Code(1, 1, 1, 1);
        code.setCompanyId(companyId);
        save(code);
        return code.getId();
    }

    public String getChemicalStorageCode(Long companyId) {return getCode(companyId, 1); }
    public String getChemicalOutCode(Long companyId) {
        return getCode(companyId, 2);
    }
    public String getWasteStorageCode(Long companyId) {
        return getCode(companyId, 3);
    }
    public String getWasteOutCode(Long companyId) {
        return getCode(companyId, 4);
    }


    public String getCode(Long companyId, int state) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        //从t_code表中查找该租户的编码记录，若无则新建
        LambdaQueryWrapper<Code> qw = new LambdaQueryWrapper<Code>();
        qw.eq(Code::getCompanyId, companyId);
        Code one = getOne(qw);
        Long codeId;
        if (one != null) {
            codeId = one.getId();
        } else {
            codeId = createCodeByCompany(companyId);
        }

        Code c = new Code();
        Integer codeNumber;
        //生成编码
        switch (state) {
            case 1:
                codeNumber = getById(codeId).getDangerousChemicalStorageCode();
                c.setDangerousChemicalStorageCode(codeNumber + 1);
                break;
            case 2:
                codeNumber = getById(codeId).getDangerousChemicalOutCode();
                c.setDangerousChemicalOutCode(codeNumber + 1);
                break;
            case 3:
                codeNumber = getById(codeId).getWasteStorageCode();
                c.setWasteStorageCode(codeNumber + 1);
                break;
            case 4:
                codeNumber = getById(codeId).getWasteOutCode();
                c.setWasteOutCode(codeNumber + 1);
                break;
            default:
                codeNumber = 0;
        }

        String code = ft.format(date) + String.format("%04d", codeNumber);

        //记录更新加1
        c.setId(codeId);
        updateById(c);
        return code;
    }
}
